/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package gui.components.basic.gui;

import gui.components.basic.gui.generic.GenericComboBoxModel;
import gui.components.basic.gui.generic.GenericComboBoxRenderer;
import gui.components.basic.gui.logic.CRUDCentral;
import gui.components.basic.gui.logic.CRUDParametrizablePanel;
import gui.components.basic.gui.logic.CRUDUpdateEntityListener;
import java.beans.Beans;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Luca
 */
public class SimpleOneToManyParamPanel extends javax.swing.JPanel implements CRUDParametrizablePanel, CRUDUpdateEntityListener {

    private Class<?> newEntityClazz;
    private Object parentObject;
    private String listFieldName;
    
    public SimpleOneToManyParamPanel(String label, Object[] initValues) {
        initComponents();
        if(!Beans.isDesignTime()){
            CRUDCentral.getInstance().addCRUDUpdateEntityListener(this);
        }
        this.jLabel1.setText(label);
        jComboBox1.setModel(new GenericComboBoxModel<Object>(initValues));
        jComboBox1.setRenderer(new GenericComboBoxRenderer<Object>());
    }

    public Class<?> getNewEntityClazz() {
        return newEntityClazz;
    }

    public void setNewEntityClazz(Class<?> newEntityClazz) {
        this.newEntityClazz = newEntityClazz;
    }

    public Object getParentObject() {
        return parentObject;
    }

    public void setParentObject(Object parentObject) {
        this.parentObject = parentObject;
    }

    public String getListFieldName() {
        return listFieldName;
    }

    public void setListFieldName(String listFieldName) {
        this.listFieldName = listFieldName;
    }
    

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jComboBox1 = new javax.swing.JComboBox();
        jButton1 = new javax.swing.JButton();

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        jLabel1.setText("ParamKey:");

        jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        jComboBox1.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                jComboBox1ItemStateChanged(evt);
            }
        });

        jButton1.setText("add");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 149, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jComboBox1, 0, 121, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton1))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(jButton1))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void jComboBox1ItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_jComboBox1ItemStateChanged
        CRUDCentral.getInstance().entitySelected(jComboBox1.getSelectedItem());
    }//GEN-LAST:event_jComboBox1ItemStateChanged

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        AddNewEntityFrame ff = new AddNewEntityFrame(this.newEntityClazz);
        ff.setLocationRelativeTo(this);
        ff.setVisible(true);
    }//GEN-LAST:event_jButton1ActionPerformed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JComboBox jComboBox1;
    private javax.swing.JLabel jLabel1;
    // End of variables declaration//GEN-END:variables

    @Override
    public void setEditable(boolean editable) {

    }

    @Override
    public boolean isEditable() {
        return true;
    }

    @Override
    public Object getValue() {
        List<Object> values = new ArrayList<Object>();
        for (int i = 0; i < jComboBox1.getItemCount(); i++) {
            values.add(jComboBox1.getItemAt(i));
        }
        return values;
    }

    @Override
    public void setValue(Object value) {
        this.jComboBox1.removeAllItems();
        if (value instanceof List) {
            List<Object> values = ((List) value);
            for (Object object : values) {
                ((GenericComboBoxModel<Object>) this.jComboBox1.getModel()).addElement(object);
            }
        }
    }

    @Override
    public void clear() {
        this.jComboBox1.removeAllItems();
    }

    @Override
    public void updateThisEntity(Class<?> entityClazz, Object id) {
        
    }

    @Override
    public void entitySelected(Object entity) {
        
    }

    @Override
    public void newEntity(Object entityClazz) {
        if(entityClazz.getClass().getCanonicalName().equals(this.newEntityClazz.getCanonicalName())){
            try {
                System.out.println("searching field: "+this.listFieldName);
                Field field = this.parentObject.getClass().getDeclaredField(listFieldName);
                field.setAccessible(true);
                List list = (List)field.get(this.parentObject);
                list.add(entityClazz);
                CRUDCentral.getInstance().updateEntity(this.parentObject);
//                CRUDCentral.getInstance().updateMe(this.parentObject.getClass(), this.parentObject.get);
            } catch (NoSuchFieldException ex) {
                Logger.getLogger(SimpleOneToManyParamPanel.class.getName()).log(Level.SEVERE, null, ex);
            } catch (SecurityException ex) {
                Logger.getLogger(SimpleOneToManyParamPanel.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IllegalArgumentException ex) {
                Logger.getLogger(SimpleOneToManyParamPanel.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IllegalAccessException ex) {
                Logger.getLogger(SimpleOneToManyParamPanel.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
}
